import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

class PasswordKey extends StatefulWidget {
  final Map lockInfo;
  const PasswordKey({super.key, required this.lockInfo});

  @override
  State<StatefulWidget> createState() => _PasswordKeyState();

}

class _PasswordKeyState extends State<PasswordKey> {
  final ScrollController _scrollController = ScrollController();
  final List<Map<String, String>> _items = [
    { "label": "重置密码", "value": "reset" },
    { "label": "隐藏失效", "value": "hide" },
  ];
  List _list = [];
  bool _isLoading = false;
  int _total = 0;
  Map<String, dynamic> _params = {
    "pageNum": 1,
    "pageSize": 10,
    "lockId": null,
  };

  Future<void> _getPwdList() async {
    try {
      EasyLoading.show();
      _isLoading = true;
      int lockId;
      if (widget.lockInfo["lockId"] is String) {
        lockId = int.parse(widget.lockInfo["lockId"]);
      } else if (widget.lockInfo["lockId"] is int) {
        lockId = widget.lockInfo["lockId"];
      } else {
        return EasyLoading.showError("lockId不存在");
      }
      Map resData = await lockApi.getPwdList(lockId, _params);
      _isLoading = false;
      EasyLoading.dismiss();
      setState(() {
        _total = resData["total"] ?? 0;
        _list.addAll(resData["rows"] ?? []);
      });
    } catch (error) {
      print("error: $error");
    }
  }

  void _getLocalPwd() {
    TTLock.getAllValidPasscode(widget.lockInfo["lockData"], (passcodeList) {
      setState(() {
        print("passcodeList:>>>>>>>>>>>>>>>>$passcodeList");
        _list = passcodeList;
      });
    }, (errorCode, errorMsg) {
      EasyLoading.showToast(errorMsg);
    });
  }

  Future<void> _resetPassword() async {
    /// 重置密码 清空锁内所有密码
    /// 添加登录密码确认重置
    taiDialog(
      context: context,
      title: "确定重置密码？",
      child: const Text("重置密码后，锁内所有密码将被清空，请谨慎操作。", textAlign: TextAlign.center,),
      onConfirm: (BuildContext taiContext) async {
        try {
          EasyLoading.show();
          await lockApi.clearPasswords(int.parse(widget.lockInfo["lockId"]));
          Stacker.pop(taiContext);
          EasyLoading.showToast("重置密码成功");
          Future.delayed(const Duration(seconds: 1));
          _refresh();
        } catch (error) {
          print("error: $error");
        }
      },
    );
  }
  
  Future<void> _delPassword(int passwordId) async {
    /// 删除密码
    taiDialog(
      context: context,
      title: "确定删除密码？",
      child: const Text("删除密码后，密码将无法使用。",textAlign: TextAlign.center,),
      onConfirm: (BuildContext taiContext) async {
        try {
          EasyLoading.show();
          await lockApi.deletePassword(int.parse(widget.lockInfo["lockId"]), passwordId);
          Stacker.pop(taiContext);
          EasyLoading.showToast("删除密码成功");
          Future.delayed(const Duration(seconds: 1));
          _refresh();
        } catch (error) {
          print("error: $error");
        }
      },
    );
  }


  Future<void> _refresh() async {
    _params["pageNum"] = 1;
    _list = [];
    _getPwdList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getPwdList();
      });
    }
  }

  Widget _listItem(Map item) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Stacker.pushNamed(Keys.DEVICE_LOCK_PASSWORDKEY_DETAIL, arguments: item);
      },
      onLongPress: () {
        /// 长按删除密码
        _delPassword(item["keyboardPwdId"]);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(5)),
          color: Colors.white,
        ),
        child: Row(
          children: [
            DecoratedBox(
              decoration: BoxDecoration(
                color: ThemeVars.colorBackground,
                borderRadius: BorderRadius.all(Radius.circular(50)),
              ),
              child: Icon(Icons.person, size: 50,),
            ),
            SizedBox(width: 10,),
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(item["keyboardPwdName"], style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),),
                        // if (item["status"] == 0) const Text("已失效", style: TextStyle(fontSize: 12, color: ThemeVars.colorError),),
                      ],
                    ),
                    const SizedBox(height: 4,),
                    Row(
                      children: [
                        Text(DateTools.formatYMD(item["endDate"], format: "{y}-{m}-{d} {h}:{i}"), style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 13),),
                        if (item["endDate"] != 0) const SizedBox(width: 10,),
                        if (item["endDate"] == 0) const Text("永久", style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 13),),
                      ],
                    )
                  ],
                )
            )
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _params["lockId"] = widget.lockInfo["lockId"];
    _getPwdList();
    // _getLocalPwd();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
        title: "密码管理",
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        showSearch: false,
        actions: [
          DropdownButton(
            icon: const Padding(padding: EdgeInsets.only(right: 12), child: Icon(Icons.more_horiz, color: Colors.white,),),
            underline: const SizedBox(height: 0,),
            padding: EdgeInsets.all(0),
            onChanged: (value) {
              if (value == "reset") {
                _resetPassword();
              } else if (value == "hide") {
                // _hidePassword();
              }
            },
            items: _items.map((item) {
              return DropdownMenuItem(
                value: item["value"],
                child: SizedBox(
                  height: 20,
                  child: Text(item["label"] ?? ""),
                ),
              );
            }).toList(),
          ),
        ],
        floatOnPress: () {
          Stacker.pushNamed(Keys.DEVICE_LOCK_PASSWORDKEY_GETKEY, arguments: widget.lockInfo)
            .then((value) {
              _refresh();
          });
        },
        children: [
          Positioned(
            width: MediaQuery.of(context).size.width,
            top: 0,
            left: 0,
            child: Container(
              width: MediaQuery.of(context).size.width,
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
              child: const SizedBox(
                height: 40,
                child: TextField(
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                      borderSide: BorderSide.none
                    ),
                    hintText: "请输入",
                    isDense: true,
                    filled: true,
                    fillColor: ThemeVars.colorBackground,
                    suffixIcon: SizedBox(
                      child: Icon(Icons.search, size: 20,),
                    ),
                  ),
                  style: TextStyle(fontSize: 14),
                ),
              )
            )
          ),
          RefreshIndicator(
            onRefresh: _refresh,
            child: Container(
              width: MediaQuery.of(context).size.width,
              margin: const EdgeInsets.only(top: 60, left: ThemeVars.paddingPage, right: ThemeVars.paddingPage),
              child: _list.isEmpty ? ListView(
                children: [EmptyData()],
              ) : ListView.separated(
                controller: _scrollController,
                physics: const AlwaysScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) => _listItem(_list[index]),
                separatorBuilder: (BuildContext context, int index) => const SizedBox(height: 12,),
                itemCount: _list.length,
              ),
            ),
          ),
        ]
    );
  }

}